﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NHibernate;

namespace Gfw.Repository
{
    /// <summary>
    /// 工作单元，用于事务管理等
    /// <para>用于多步操作执行时</para>
    /// </summary>
    public class UnitOfWork
    {

        #region 打开数据库连接
        private ISession _session;
        ITransaction trans;
        public virtual ISession Session
        {
            get
            {
                if (_session == null)
                    _session = RepositoryFactory.OpenSession();
                return _session;
            }
        }
        #endregion

        #region 构造函数和初始化
        public UnitOfWork()
        {
            trans = this.Session.BeginTransaction();
        }
        public UnitOfWork(bool manual)
        {
            if (manual == false)
                trans = this.Session.BeginTransaction();
        }

        #endregion

        #region 通过的方法

        public virtual T Load<T>(string id) where T:class
        {
            var reslut = Session.Load<T>(id);
            return reslut ?? default(T);
        }

        public virtual T Get<T>(string id) where T : class
        {
            var reslut = Session.Get<T>(id);
            return reslut ?? default(T);
        }



        public virtual void Save<T>(T entity)
        {
            Session.Save(entity);
            Session.Flush(); // 同步到数据库
        }

        public virtual IEnumerable<T> GetAll<T>() where T : class
        {
            return Session.CreateCriteria<T>()
               .List<T>();
        }

        public virtual void SaveOrUpdate<T>(T entity)
        {
            Session.SaveOrUpdate(entity);
            Session.Flush(); // 同步到数据库
        }
        public virtual void Update<T>(T entity)
        {
            Session.Update(entity);
            Session.Flush(); // 同步到数据库
        }
        public virtual void Delete<T>(string id) where T : class
        {
            var entity = Get<T>(id);
            Session.Delete(entity);
            Session.Flush(); // 同步到数据库
        }

        #endregion 通用的方法

        #region 事务
        public void BeginTransaction()
        {
            trans = this.Session.BeginTransaction();
        }

        /// <summary>
        /// 对于乐观锁的事务，这里应该控制？？？？
        /// </summary>
        public void  Commit()
        {
            try
            {
                trans.Commit();
               
            }
            catch (Exception ex)
            {
                trans.Rollback();
                throw ex;
            }
        }

        public void Rollback()
        {
            trans.Rollback();
        }
        #endregion
    }
}
